package com.org.redis.utils;

import org.springframework.beans.factory.annotation.Value;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

public class FastUtils {

    public static Object loadBean(String classInfo, String propertiesName) throws Exception {
        Properties properties = new Properties();
        InputStream in = FastUtils.class.getClassLoader().getResourceAsStream(propertiesName);
        properties.load(in);

        Class clazz = Class.forName(classInfo);
        Object instance = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();

        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        List<PropertyDescriptor> descriptors = Arrays.stream(beanInfo.getPropertyDescriptors()).collect(Collectors.toList());

        for (Field field : fields) {
            if (!field.isAnnotationPresent(Value.class)) {
                continue;
            }
            Value value = field.getAnnotation(Value.class);
            String s = value.value();
            PropertyDescriptor descriptor = new PropertyDescriptor(field.getName(), clazz);

            Method writeMethod = descriptor.getWriteMethod();
            writeMethod.setAccessible(true);
            Object prop = properties.get(s);
            if (prop != null) {
                writeMethod.invoke(instance, get(prop,  field.getType()));
            }
        }
        return instance;
    }

    public static Object get(Object o, Class<?> t){
        if(t != null){
            if (isNumeric(o)) {
                Integer i = Integer.parseInt(o.toString());
                return i.intValue();
            }
            return t.cast(o);
        }
        return null;
    }

    public static boolean isNumeric(Object obj) {
        if (obj == null) {
            return false;
        }
        char[] chars = obj.toString().toCharArray();
        int length = chars.length;
        if (length < 1) {
            return false;
        }

        int i = 0;
        if (length > 1 && chars[0] == '-') {
            i = 1;
        }

        for (; i < length; i++) {
            if (!Character.isDigit(chars[i])) {
                return false;
            }
        }
        return true;
    }
}
